"""Language detection module"""

from typing import Optional, Dict, List
from langdetect import detect, DetectorFactory
import logging
import re

# 设置种子以确保结果一致性
DetectorFactory.seed = 0

class LanguageDetector:
    """Language detector implementation"""
    
    def __init__(self):
        self.logger = logging.getLogger(self.__class__.__name__)
        self.supported_languages = {
            'en': 'English',
            'zh': 'Chinese',
            'fr': 'French',
            'de': 'German',
            'es': 'Spanish',
            'ja': 'Japanese'
        }
        
        # 语言特征模式
        self.language_patterns = {
            'zh': r'[\u4e00-\u9fff]',  # 中文字符
            'en': r'[a-zA-Z]',         # 英文字符
            'ja': r'[\u3040-\u30ff]',  # 日文假名
        }
        
        # 语言代码映射
        self.lang_mapping = {
            'zh-cn': 'zh',
            'zh-tw': 'zh',
            'zh-sg': 'zh',
            'zh-hk': 'zh',
            'eng': 'en',
            'cmn': 'zh',
            'chi': 'zh',
            'chs': 'zh',
            'cht': 'zh',
            'jpn': 'ja',
            'ko': 'zh',  # 修复韩语误判
            'tl': 'en'   # 修复他加禄语误判
        }
    
    def _count_language_chars(self, text: str) -> Dict[str, int]:
        """统计文本中各种语言字符的数量"""
        counts = {}
        for lang, pattern in self.language_patterns.items():
            counts[lang] = len(re.findall(pattern, text))
        return counts
    
    def _get_dominant_language(self, text: str) -> Optional[str]:
        """根据字符统计确定主要语言"""
        counts = self._count_language_chars(text)
        total_chars = sum(counts.values())
        
        if total_chars == 0:
            return None
            
        # 计算各语言字符的比例
        ratios = {lang: count/total_chars for lang, count in counts.items()}
        
        # 如果中文字符超过30%，认为是中文
        if ratios.get('zh', 0) > 0.3:
            return 'zh'
        # 如果英文字符超过50%，认为是英文
        elif ratios.get('en', 0) > 0.5:
            return 'en'
        # 如果日文字符超过30%，认为是日文
        elif ratios.get('ja', 0) > 0.3:
            return 'ja'
            
        return None
    
    async def detect_language(self, text: str) -> Optional[str]:
        """
        Detect the language of input text.
        
        Args:
            text (str): Input text
            
        Returns:
            Optional[str]: Language code (e.g., 'en', 'zh') or None if detection fails
        """
        try:
            # 预处理文本
            text = text.strip()
            if not text:
                self.logger.warning("Empty text provided")
                return None
                
            # 首先尝试基于字符特征的检测
            dominant_lang = self._get_dominant_language(text)
            if dominant_lang:
                self.logger.info(f"Detected language by character analysis: {self.supported_languages[dominant_lang]} ({dominant_lang})")
                return dominant_lang
            
            # 如果字符分析无法确定，使用 langdetect
            self.logger.debug(f"Detecting language for text: {text[:50]}...")
            detected = detect(text)
            
            # 映射语言代码
            detected = self.lang_mapping.get(detected, detected)
            
            if detected in self.supported_languages:
                self.logger.info(f"Detected language: {self.supported_languages[detected]} ({detected})")
                return detected
            else:
                self.logger.warning(f"Detected unsupported language: {detected}")
                return None
                
        except Exception as e:
            self.logger.error(f"Language detection failed: {str(e)}")
            return None
    
    def is_supported_language(self, lang_code: str) -> bool:
        """Check if a language is supported"""
        return lang_code in self.supported_languages
    
    def get_supported_languages(self) -> dict:
        """Get all supported languages"""
        return self.supported_languages.copy()
